<template>
  <div class="hi-breadcrumb">
    <template v-if="pathInfo && pathInfo.length > 1">
      <el-breadcrumb :separator-icon="ArrowRight">
        <template v-for="(item, index) in pathInfo" :key="item.id">
          <el-breadcrumb-item>
            <span v-if="index == pathInfo.length - 1">
              {{ props.detailLabel ? props.detailLabel : item.name }}
            </span>
            <router-link v-else @click="clickPath(index)" to="">
              {{ item.name }}
            </router-link>
          </el-breadcrumb-item>
        </template>
      </el-breadcrumb>
    </template>
  </div>
</template>

<script setup lang="ts">

import {onMounted, ref} from "vue";
import {ArrowRight} from "@element-plus/icons-vue";
import {useRouter} from "vue-router";

const props = withDefaults(defineProps<{
  detailLabel?: string,
  triggerPath?: any,
  rootPath: any,
}>(), {});

const router = useRouter();
const pathInfo = ref();
const rootRoute = ref();

onMounted(() => {
  pathInfo.value = [];
  pathInfo.value.push({
    ...props.rootPath
  });
  rootRoute.value = router.currentRoute.value.path;
})

const getRoutePath = () => {
  let skipPath = rootRoute.value;

  if (skipPath.endsWith('/')) {
    skipPath = skipPath.substring(0, skipPath.length - 1);
  }

  pathInfo.value.forEach((id: any) => {
    if (id.id) {
      skipPath += '/' + id.id;
    }
  })

  return skipPath;
}

const clickPath = (index: number) => {
  const currItem: any = pathInfo.value[index];
  const current = {...currItem};
  pathInfo.value.splice(index + 1, pathInfo.value.length - index - 1);
  const currPath = getRoutePath();

  // 由于上面采用的是COPY的方式，这里需要把刷新标志删除，防止每次
  // 点击面包屑都刷新界面
  delete currItem.needRefresh;

  if (props.triggerPath) {
    props.triggerPath(current, currPath);
  }

  return currPath;
}

const routeToPath = (item: any) => {
  delete item.needRefresh;
  const rItem: any = {...item};
  pathInfo.value?.push(rItem);
  return getRoutePath();
}

const routeToRoot = () => {
  pathInfo.value = [];
  pathInfo.value.push({...props.rootPath});
  return getRoutePath();
}

const getCurrent = () => {
  return pathInfo.value[pathInfo.value.length - 1];
}

const setRefreshRoot = () => {
  if (pathInfo.value && pathInfo.value.length > 0) {
    pathInfo.value[0].needRefresh = true;
  }
}

defineExpose({
  routeToPath,
  routeToRoot,
  getRoutePath,
  getCurrent,
  setRefreshRoot,
})

</script>

<style>
.hi-breadcrumb {
  display: flex;
  flex-direction: row;
  margin-bottom: 8px;
}

</style>
